﻿@model Entity.WarehouseEditDTO
@using Entity;
@{
    ViewData["Title"] = "编辑仓库";
    // 安全处理：避免ViewBag数据为null导致的异常
    var warehouse = ViewBag.Warehouse as WarehouseEditDTO ?? new WarehouseEditDTO();
    var organizations = ViewBag.Organizations as List<SysOrgOrganizations> ?? new List<SysOrgOrganizations>();
    var warehouseManagers = ViewBag.WarehouseManagers as List<SysOrgUserManagement> ?? new List<SysOrgUserManagement>();
    var statusList = ViewBag.WarehouseStatusList as List<WarehouseStatusDTO> ?? new List<WarehouseStatusDTO>();
}

<!-- 引入Vue 3和Element Plus依赖（放在body顶部，避免与布局页head冲突） -->
<script src="https://unpkg.com/vue@3.3.4/dist/vue.global.prod.js"></script>
<link rel="stylesheet" href="https://unpkg.com/element-plus@2.4.2/dist/index.css">
<script src="https://unpkg.com/element-plus@2.4.2/dist/index.full.min.js"></script>

<!-- 添加CSRF令牌meta标签（用于表单提交验证） -->
<meta name="csrf-token" content="@Context.Request.Cookies["XSRF-TOKEN"]" />

<!-- Vue挂载点（必须存在，否则Vue无法渲染） -->
<div id="app">
    <div class="container mt-5">
        <h2 class="mb-4 fw-bold">编辑仓库</h2>
        <el-card>
            <!-- 使用Element Plus的表单验证功能 -->
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="mt-4">
                <!-- 仓库ID（隐藏域） -->
                <el-form-item prop="WarehouseId">
                    <el-input v-model="form.WarehouseId" type="hidden"></el-input>
                </el-form-item>

                <!-- 仓库编号 -->
                <el-form-item label="仓库编号" prop="WarehouseNumber">
                    <el-input v-model="form.WarehouseNumber" placeholder="请输入仓库编号"></el-input>
                </el-form-item>

                <!-- 仓库名称 -->
                <el-form-item label="仓库名称" prop="WarehouseName">
                    <el-input v-model="form.WarehouseName" placeholder="请输入仓库名称"></el-input>
                </el-form-item>

                <!-- 仓库容量 -->
                <el-form-item label="仓库容量(m³)" prop="WarehouseCapacity">
                    <el-input v-model.number="form.WarehouseCapacity" type="number" placeholder="请输入仓库容量"></el-input>
                </el-form-item>

                <!-- 库管部门 -->
                <el-form-item label="库管部门" prop="OrgId">
                    <el-select v-model="form.OrgId" placeholder="请选择库管部门">
                        @foreach (var org in organizations)
                        {
                            <el-option label="@org.organization_name" :value="@org.organization_id"></el-option>
                        }
                    </el-select>
                </el-form-item>

                <!-- 仓库主管 -->
                <el-form-item label="仓库主管" prop="ManagerId">
                    <el-select v-model="form.ManagerId" placeholder="请选择仓库主管">
                        @foreach (var user in warehouseManagers)
                        {
                            <el-option label="@user.UserName" :value="@user.UserId"></el-option>
                        }
                    </el-select>
                </el-form-item>

                <!-- 仓库地址 -->
                <el-form-item label="仓库地址" prop="Address">
                    <el-input v-model="form.Address" placeholder="请输入仓库地址"></el-input>
                </el-form-item>

                <!-- 是否默认仓库 -->
                <el-form-item label="是否默认">
                    <el-switch v-model="form.IsDefault" active-text="是" inactive-text="否"></el-switch>
                </el-form-item>

                <!-- 排序号 -->
                <el-form-item label="排序号" prop="Sorting">
                    <el-input v-model.number="form.Sorting" type="number" placeholder="请输入排序号（数字越大越靠前）"></el-input>
                </el-form-item>

                <!-- 状态 -->
                <el-form-item label="仓库状态" prop="Status">
                    <el-select v-model="form.Status" placeholder="请选择状态">
                        @foreach (var status in statusList)
                        {
                            <!-- 修复状态值绑定语法，确保正确转换为数字类型 -->
                            <el-option label="@status.StatusName" :value="parseInt(@status.StatusValue)"></el-option>
                        }
                    </el-select>
                </el-form-item>

                <!-- 关联库位 -->
                <el-form-item label="关联库位" prop="SelectedLocationIds">
                    <el-select v-model="form.SelectedLocationIds"
                               multiple
                               placeholder="请选择库位"
                               :loading="locationLoading">
                        <el-option v-for="location in locationList"
                                   :key="location.location_id"
                                   :label="`${location.location_number}（${location.location_name}）`"
                                   :value="location.location_id"></el-option>
                    </el-select>
                </el-form-item>

                <!-- 备注 -->
                <el-form-item label="备注" prop="Note">
                    <el-input v-model="form.Note" type="textarea" rows="3" placeholder="请输入备注信息"></el-input>
                </el-form-item>

                <!-- 操作按钮（修复事件绑定空格问题） -->
                <el-form-item>
                    <el-button type="primary" @@click ="submitForm">保存</el-button>
                    <el-button @@click ="resetForm">重置</el-button>
                    <el-button type="text" @@click ="goBack">返回</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</div>

<script>
    // 从Vue全局对象中获取需要的API
    const { createApp, ref, reactive, onMounted } = Vue;
    // 从ElementPlus全局对象中获取组件
    const { ElMessage } = ElementPlus;

    createApp({
        setup() {
            // 表单引用（用于验证）
            const formRef = ref(null);

            // 库位加载状态
            const locationLoading = ref(false);
            // 库位列表数据
            const locationList = ref([]);

            // 初始化表单数据（确保序列化格式正确）
            const form = reactive(@Html.Raw(
                warehouse != null && warehouse.WarehouseId > 0
                    ? Newtonsoft.Json.JsonConvert.SerializeObject(warehouse)
                    : "{}"
            ));

            // 表单验证规则
            const rules = reactive({
                WarehouseNumber: [
                    { required: true, message: '请输入仓库编号', trigger: 'blur' },
                    { max: 50, message: '编号长度不能超过50个字符', trigger: 'blur' }
                ],
                WarehouseName: [
                    { required: true, message: '请输入仓库名称', trigger: 'blur' },
                    { max: 100, message: '名称长度不能超过100个字符', trigger: 'blur' }
                ],
                WarehouseCapacity: [
                    { required: true, message: '请输入仓库容量', trigger: 'blur' },
                    { type: 'number', min: 0.01, message: '容量必须大于0', trigger: 'blur' }
                ],
                OrgId: [
                    { required: true, message: '请选择库管部门', trigger: 'change' }
                ],
                ManagerId: [
                    { required: true, message: '请选择仓库主管', trigger: 'change' }
                ],
                Status: [
                    { required: true, message: '请选择仓库状态', trigger: 'change' }
                ],
                SelectedLocationIds: [
                    { required: true, message: '请至少选择一个库位', trigger: 'change' }
                ],
                Address: [
                    { max: 200, message: '地址长度不能超过200个字符', trigger: 'blur' }
                ],
                Note: [
                    { max: 500, message: '备注长度不能超过500个字符', trigger: 'blur' }
                ]
            });

            // 页面加载时获取库位数据
            onMounted(async () => {
                await loadLocationList();
            });

            // 加载所有可用库位
            const loadLocationList = async () => {
                locationLoading.value = true;
                try {
                    const response = await fetch('@Url.Action("GetStorageLocationPagedList", "Warehouse")?pageSize=1000');
                    if (!response.ok) throw new Error(`HTTP错误：${response.status}`);

                    const result = await response.json();
                    if (result.code === 200 && result.data?.data) {
                        // 过滤已删除的库位，并确保location_id为数字类型
                        locationList.value = result.data.data
                            .filter(item => item.is_delete === 0)
                            .map(item => ({
                                ...item,
                                location_id: parseInt(item.location_id)
                            }));
                    } else {
                        ElMessage.warning('获取库位列表失败：' + (result.message || '未知错误'));
                    }
                } catch (err) {
                    console.error('加载库位数据失败：', err);
                    ElMessage.error(`加载库位失败：${err.message}`);
                } finally {
                    locationLoading.value = false;
                }
            };

            // 提交表单
            const submitForm = async () => {
                if (!formRef.value) return;
                // 表单验证
                const valid = await formRef.value.validate().catch(() => false);
                if (!valid) return;

                try {
                    const response = await fetch('@Url.Action("Edit", "Warehouse")', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || ''
                        },
                        body: JSON.stringify(form)
                    });
                    const result = await response.json();

                    if (result.code === 200) {
                        ElMessage.success(result.message || '保存成功');
                        setTimeout(() => window.location.href = '@Url.Action("Index", "Warehouse")', 1000);
                    } else {
                        ElMessage.error(result.message || '保存失败');
                    }
                } catch (err) {
                    console.error('提交表单失败：', err);
                    ElMessage.error(`提交失败：${err.message}`);
                }
            };

            // 重置表单
            const resetForm = () => {
                if (formRef.value) {
                    formRef.value.resetFields();
                }
                // 重置为初始数据
                Object.assign(form, @Html.Raw(
                    warehouse != null && warehouse.WarehouseId > 0
                        ? Newtonsoft.Json.JsonConvert.SerializeObject(warehouse)
                        : "{}"
                ));
            };

            // 返回列表
            const goBack = () => {
                window.location.href = '@Url.Action("Index", "Warehouse")';
            };

            return {
                formRef,
                form,
                rules,
                locationList,
                locationLoading,
                submitForm,
                resetForm,
                goBack
            };
        }
    }).use(ElementPlus).mount('#app');
</script>